/*
 * Copyright (c) 2010, VeRSI Consortium
 *   (Victorian eResearch Strategic Initiative, Australia)
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the VeRSI, the VeRSI Consortium members, nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package versi.vitro.oaiserviceprovider.xml;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;

import versi.vitro.oaiserviceprovider.helper.GeneralHelper;

/** The DOM entity resource resolver. */
public class ResourceResolver implements LSResourceResolver {

    /** log4j instance. */
    private static final Logger LOGGER = Logger.getLogger(ResourceResolver.class);

    /** General utility helper. */
    private GeneralHelper helper;

    /** XML namespace constant. */
    private static final String XML_NAMESPACE_URI = "http://www.w3.org/2001/xml.xsd";

    /** XML Schema constant. */
    private static final String SCHEMA_URI = "http://www.w3.org/2001/XMLSchema.xsd ";

    private static final Map<String, String> NSFILEMAP = new HashMap<String, String>();

    static {
	NSFILEMAP.put(XML_NAMESPACE_URI, "xml.xsd");
	// NSFILEMAP.put(WSDL_NAMESPACE_URI, "wsdl.xsd");
	NSFILEMAP.put(SCHEMA_URI, "XMLSchema.xsd");
    }

    /**
     * Default Constructor.
     */
    public ResourceResolver(GeneralHelper helper) {
	super();
	this.helper = helper;
    }

    /**
     * Resolves resource within XML schema.
     * 
     * @param type
     * @param namespaceURI
     * @param publicId
     *            The public identifier for this input source.
     * @param systemId
     *            The system identifier, a URI reference [IETF RFC 2396], for
     *            this input source.
     * @param baseURI
     *            The base URI to be used (see section 5.1.4 in [IETF RFC 2396])
     *            for resolving a relative systemId to an absolute URI.
     * 
     */
    public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
	if (LOGGER.isDebugEnabled()) {
	    LOGGER.debug(systemId);
	}
	InputStream resourceAsStream = null;
	if (systemId.startsWith("http://") || systemId.startsWith("https://")) {
	    resourceAsStream = retrieveRemoteResource(systemId);
	} else {
	    resourceAsStream = retrieveLocalResource(systemId);
	}
	return new Input(publicId, systemId, resourceAsStream);
    }

    /**
     * Retrieves remote resource.
     * 
     * @param systemId
     * @return InputStream
     */
    protected InputStream retrieveRemoteResource(String systemId) {
	InputStream resourceAsStream = null;
	try {
	    URL url = (new URL(systemId));
	    URLConnection urlConnection = url.openConnection();
	    resourceAsStream = urlConnection.getInputStream();
	} catch (FileNotFoundException fnfException) {
	    String message = "Unable to resolve resource during XML processing as remote resource not found. ";
	    LOGGER.fatal(message, fnfException);
	    throw new RuntimeException(message, fnfException);
	} catch (MalformedURLException mfUrlException) {
	    String message = "Unable to resolve resource during XML processing as URL of remote resource is malformed. ";
	    LOGGER.fatal(message, mfUrlException);
	    throw new RuntimeException(message, mfUrlException);
	} catch (IOException ioException) {
	    String message = "Unable to resolve resource during XML processing as resouce could not be read. ";
	    LOGGER.fatal(message, ioException);
	    throw new RuntimeException(message, ioException);
	}
	return resourceAsStream;
    }

    /**
     * Retrieves local resource.
     * 
     * @param systemId
     * @return InputStream
     */
    protected InputStream retrieveLocalResource(String systemId) {
	byte[] fileContents = helper.getFileAsByteArray(new File(systemId));
	InputStream resourceAsStream = createInputStream(fileContents);
	return resourceAsStream;
    }

    /**
     * Create an InputStream from
     * 
     * @param fileContents
     *            Array of bytes represents the file contents.
     * @return InputStream
     */
    protected InputStream createInputStream(byte[] fileContents) {
	return new BufferedInputStream(new ByteArrayInputStream(fileContents));
    }

}
